﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.IO.Ports;

namespace lbc_02_emulator
{
    public partial class MainWindow : Form
    {
        bool m_AjusteTemps, m_State, m_ModeContinue, m_connected;
        SerialPort m_connexion = new SerialPort();
        CTrame[] m_Tramme = new CTrame[10];
        int m_PresentIndex;

        public MainWindow()
        {
            InitializeComponent();
            m_AjusteTemps = m_State = m_connected = false;
            m_ModeContinue = false;
            m_PresentIndex = 0;
        }

        ~MainWindow()
        {
            m_connexion.Close();
            m_connexion.Dispose();
        }

        private bool CheckHeure()
        {
            bool retour = true;

            if (txt_Heure.TextLength > 2 || txt_Minute.TextLength > 2)
                retour = false;
            int longueur = txt_Heure.TextLength;
            for (int i = 0; i < longueur; i++)
                if (char.IsDigit(txt_Heure.Text[i]) == false)
                    retour = false;
            longueur = txt_Minute.TextLength;
            for (int i = 0; i < longueur; i++)
                if (char.IsDigit(txt_Minute.Text[i]) == false)
                    retour = false;

            return retour;
        }
        private void btn_Test_Click(object sender, EventArgs e)
        {
            //m_Tramme[0] = new CTrame("4", 1);
            //m_Tramme[0].GetByte();
        }

        private void radioConfig_CheckedChanged(object sender, EventArgs e)
        {
             RadioButton rb = sender as RadioButton;

             switch (rb.Text)
             {
                 case "Ajuster":
                     m_AjusteTemps = true;
                     txt_Heure.Enabled = true;
                     txt_Minute.Enabled = true;
                     break;
                 case "Maintenant":
                     m_AjusteTemps = false;
                     txt_Minute.Enabled = false;
                     txt_Heure.Enabled = false;
                     break;
                     // pour l'instant, on ne fonctionne qu'en mode continue
                     // on laisse donc les deux à false
                 case "Continue":
                     m_ModeContinue = false;
                     break;
                 case "SOH":
                     m_ModeContinue = false;
                     break;
             }
        }

        private void btn_Connect_Click(object sender, EventArgs e)
        {
            bool error = false;
            int index = lst_Port.SelectedIndex;
            string port = "", speed = "";
            if (index >= 0)
                port = lst_Port.Items[index].ToString();
            else
                error = true;
            index = lst_Speed.SelectedIndex;
            if (index >= 0)
                speed = lst_Speed.Items[index].ToString();
            else
                error = true;
            
            if (error == false)
            {
                try
                {
                    m_connexion.PortName = port;
                    m_connexion.BaudRate = Convert.ToInt32(speed);
                    m_connexion.Parity = System.IO.Ports.Parity.None;
                    m_connexion.ReadTimeout = 5000; // lire 5 secondes
                    m_connexion.Open();
                    grp_Tramme.Enabled = true;
                    btn_Connect.Enabled = false;
                    btn_Deconnect.Enabled = true;
                    txt_State.Text = "CONNECTÉ!";
                }
                catch (Exception exc)
                {
                    MessageBox.Show(exc.ToString());
                    txt_State.Text = "ERREUR!";
                }
            }
            else
                MessageBox.Show("Assurez-vous d'avoir bien selectionné une vitesse et un port");
        }

        private void btn_Deconnect_Click(object sender, EventArgs e)
        {
            try
            {
                m_connexion.Close();
                grp_Tramme.Enabled = false;
                btn_Deconnect.Enabled = false;
                btn_Connect.Enabled = true;
                txt_State.Text = "Déconnecté";
            }
            catch (System.IO.IOException exc)
            {
                MessageBox.Show(exc.ToString());
                txt_State.Text = "ERREUR!";
            }
        }

        private void btn_Send_Click(object sender, EventArgs e)
        {
            int byteReceived = 0;
            if (txt_Data.TextLength > 0)
            {
                if (m_AjusteTemps == false)
                    m_Tramme[0] = new CTrame(txt_Data.Text, 1);
                else
                {
                    // Vérification du format heure et minute donné par l'usager
                    if (CheckHeure())
                        m_Tramme[0] = new CTrame(txt_Data.Text, 0, txt_Heure.Text, txt_Minute.Text);
                    else
                    {
                        MessageBox.Show("Vous devez entrer heure et minutes sous le format 00 et 00");
                        return;
                    }
                }
                int longueur = m_Tramme[0].ToString().Length;
                m_connexion.Write(m_Tramme[0].GetByte(), 0, longueur);
                //MessageBox.Show(m_Tramme[0].ToString());
            }
            else
                MessageBox.Show("Vous devez mettre au moins un caractère dans la boîte d'édition");

            // À partir d'ici, on écoute pour le retour si on est en mode SOH
            if (m_ModeContinue == true)
            {
                bool paquetRetour = false;
                while (paquetRetour == false)
                {
                    try
                    {
                        byteReceived = m_connexion.ReadChar();
                        MessageBox.Show(byteReceived.ToString());
                    }
                    catch
                    {
                        //byteReceived = 21;
                    }
                    if (byteReceived == 65)
                        paquetRetour = true;
                    if (byteReceived == 21)
                        this.btn_Send_Click(sender, e);
                }
                MessageBox.Show("False");
                if (paquetRetour == false)
                    this.btn_Send_Click(sender, e);
                MessageBox.Show("Traversé");
            }
        }

        private void m_About_Click(object sender, EventArgs e)
        {
            About a = new About();
            a.Show();
        }
    }
}
